//是否显示收货时间
  setTimeout(function(){$(".applyHint").css("height","auto")},200)
//判断是否微信
   var wechat=false;
   var ua = navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i)=="micromessenger") {
	   wechat=true;	
    } 

//初始化数据
	   localStorage.crowdCode=initData.crowdCode;
	   var crowdedNum=initData.crowdedNum;
	   var crowdCode=initData.crowdCode;
	  
       var crowdType=crowdCode.slice(0,2); 
	   
//判断终端与活动

  if(wechat==false){
	  $(".CrowdTel").remove(); 
	  $(".applyListApp").remove();
	   $(".voiceButton").remove();
  }else{
	  $(".applyListApp").remove();
  }
//获取当前时间
   var current=new Date();
       var currentHour=current.getHours();
//页面初始化内容
   $("#crowdName").html(initData.crowdTitle);

//周末牛排限时抢特殊规则
//用户选择时间

	  $("#time").change(function(){	  
		  selectSpan();
		    var time=$('#time option:selected').val(); 
			$(".timeSpan").html(time);
		  if($('#time option:selected').val()=="待定"){$(".clockSpan").html("待定");}
		  var clockLength=$("#clock option").length;
          if($('#time option:selected').val()=="今天"){
			  if( Number(($('#clock option:selected').val().slice(0,2)))<Number(currentHour)+4){
				   commonTckBlack("收货时间至少提前三小时");
                  $("#clock option").eq(Number(currentHour)+4).attr("selected","selected")
				  selectSpan()
				   var clock=$('#clock option:selected').val();
				   $(".clockSpan").html(clock); 
			  }
		  }
		
	  })
	  $("#clock").change(function(){
		 var clock=$('#clock option:selected').val(); 
	    $(".clockSpan").html(clock);
		 if($('#time option:selected').val()=="待定"){
			 $(".clockSpan").html("待定");
			  commonTckBlack("您已选择了日期待定");
			 }
		 if($('#time option:selected').val()=="今天"){
			  if( Number(($('#clock option:selected').val().slice(0,2)))<Number(currentHour)+4){
				   commonTckBlack("收货时间至少提前三小时");
                  $("#clock option").eq(Number(currentHour)+4).attr("selected","selected")
				   var clock=$('#clock option:selected').val(); 
	    $(".clockSpan").html(clock);
			  }
		  }
	  })
//初始化未来30天的日期，并加入到select中
     var Week = ['日','一','二','三','四','五','六'];
	 var endDate=new Date(initData.endTime);
	 var showDate=parseInt((endDate-current)/(1000*60*60*24))+1;
     function getNextDay(i){
        var d = new Date();
        d = +d + 1000*60*60*24*i;
        d = new Date(d);
		var c=d.getDay();
		var y=d.getFullYear();

		var a=String(d.getMonth()+1)
		if (a.length==1){
			a="0"+a;
			}
		var b=String(d.getDate());
		if(b.length==1){
			b="0"+b;
			}
		return (y+"年"+a+"月"+b+"日"+" 星期"+Week[c]); 
        }
		
     for(var i=0;i<showDate;++i){
         var node1 = document.createElement("option");
		 node1.innerHTML=getNextDay(i);
		 document.getElementById("time").appendChild(node1)	
	    } 
	 $("#time option").eq(2).html("今天");
     if(dateLimit==1){
		  $("#time option").eq(1).remove();
		  $("#time option").eq(1).remove();
		  $("#time option").eq(1).remove();
		 }

	  $("#province").change(function(){
		 selectSpan();
	  })
	  $("#city").change(function(){
		 selectSpan();
	  })
	  //地区选择
	  $("#addressSelect").show();
	  $("#contactAddress").attr("placeholder","请填写详细地址(区域街道门牌号等)")
	  
	  
	    
//初始化选择
function selectSpan(){
		var province=$('#s_province option:selected').val(); 
	    $(".provinceSpan").html(province);
		var city=$('#s_city option:selected').val(); 
	    $(".citySpan").html(city);
		var county=$('#s_county option:selected').val(); 
	    $(".areaSpan").html(county);
	  };
	  
//用户增加或者减少用餐人数的操作

       $(".reduceButton").bind("touchstart",function(e){ 
	       $(this).find("img").attr("src",styleUrl+"/styles/img/reduceIconHover.png");  
	       var peopleNum=Number($(this).siblings(".buyNumber").val()); 
		   if(peopleNum==0){
		     commonTckBlack("购买数量不能小于0");
			 $(this).siblings(".buyNumber").val(0);
			 return;
		    }
			peopleNum=Number(peopleNum)-1;
			$(this).siblings(".buyNumber").val(peopleNum);
			totalPrice();
		  },false)
	   $(".reduceButton").bind("touchend",function(e){
		    $(this).find("img").attr("src",styleUrl+"/styles/img/reduceIcon.png"); 
		   })
	   $(".addButton").bind("touchstart",function(e){ 
	       $(this).find("img").attr("src",styleUrl+"/styles/img/addIconHover.png");

	       var peopleNum=Number($(this).siblings(".buyNumber").val()); 
		
			peopleNum=Number(peopleNum)+1;
			$(this).siblings(".buyNumber").val(peopleNum);
			totalPrice();
		  },false)
	    $(".addButton").bind("touchend",function(e){
		   $(this).find("img").attr("src",styleUrl+"/styles/img/addIcon.png"); 
		   })
	   $(".buyNumber").change(function(){
		   var peopleNum=Number($(this).val());
           if(isNaN(peopleNum)){
			  commonTckBlack("请输入数字");
			   $(this).val(1); 
		   }		   
		   if(peopleNum<0){
			   commonTckBlack("购买数量不能小于0");
			   $(this).val(0);
			   }
		   totalPrice();
		})
//地址发票弹出框管理按钮
 
//地址发票弹出框管理按钮

   $("#addressButton").click(function(){
      $(".addressTck").fadeIn();
	  $(".applySelectBg").fadeIn();
   })
   //地址完成赋值
  $("#addressSubmit").click(function(){
    var name=$("#contactName").val();
	var tel=$("#contactTel").val();
	var address=$("#contactAddress").val();
	if(name!=""||tel!=""||address!=""){
	   $("#applyName").html(name);
	   $("#applyTel").html(tel);
	   $("#applyAddress").html(address)
	//周末牛排限时抢特殊规则

		   var showProvince=$("#s_province option:selected").val();
		   var showCity=$("#s_city option:selected").val();
		   var showCounty=$("#s_county option:selected").val();
		   
		 if(showProvince=="省份")showProvince="";
		 if(showCity=="地级市")showCity="";
		 if(showCounty=="市、县级市")showCounty=""; 
		 //将填写的地址保存在本地
		 var addressInfo={
			 "name":name,
			 "tel":tel,
			 "province":showProvince,
			 "city":showCity,
			 "county":showCounty,
			 "address":address
			 }
		 localStorage.addressInfo=JSON.stringify(addressInfo);
		 if(showProvince==showCity){
			showCity="";
			 }
		
	    $("#applyAddress").html(showProvince+showCity+showCounty+address)
	   $(".addressLiDetail").show();
	   $("#addressHint").hide();
	 }
	 else{
	   $("#applyName").html(name);
	   $("#applyTel").html(tel);
	   $("#applyAddress").html(address);
	   $(".addressLiDetail").hide();
	   $("#addressHint").show();
	 }
	$(".addressTck").fadeOut();
	$(".applySelectBg").fadeOut();
  })

   $(".applySelectBg").click(function(){
      $(".remarkTck").fadeOut();
	  $(".addressTck").fadeOut();
	  $(".applySelectBg").fadeOut();
   })

//倒计时
	var second;
	var secondReduce;
	function countDown(){
		$(".countDown").show();
		second=60;
	    secondReduce=setInterval("secondDown()",1000);
		}	
	function secondDown(){
		    second=second-1;
			$(".countDown").html(second+"秒");
			if(second==0){
				$(".countDown").html("60秒").hide();
				$("#getCode").html("重新获取");
				clearInterval(secondReduce);
			  }
			}	
//发送验证码
    if(wechat==true){
		document.getElementById("getCode").addEventListener("click",function(e){
		checkTel(function(tel){//检查手机号填写
		      if($("#contactTel").val()==""&&$("#applyTel").html()==""){
				  $("#contactTel").val(tel); 
			      $("#applyTel").html(tel);
				  }	  
			  $.post(initData.getCodeApi,{"phoneNo":tel,"deviceId":"w_"+initData.userOpenId},function(){
				  countDown();
				  })
			},false)})
	}
//语音验证码
    $(".voiceButton a").click(function(e) {
		$(".applySelectBg").fadeIn();
        $(".videoLog").fadeIn();
    });
	$(".default").click(function(e) {
        $(".applySelectBg").fadeOut();
        $(".videoLog").fadeOut();
    });
	
	$(".primary").click(function(e) {
		$(".applySelectBg").fadeOut();
        $(".videoLog").fadeOut();
        checkTel(function(tel){//检查手机号填写
		      if($("#contactTel").val()==""&&$("#applyTel").html()==""){
				  $("#contactTel").val(tel); 
			      $("#applyTel").html(tel);
				  }	      
			  $.post(initData.getVoiceCodeApi,{"phoneNo":tel,"deviceId":"w_"+initData.userOpenId},function(data){
				 if(Number(data.success)==1){
					 commonTckBlack("发送成功！请留意您的来电。");
					 }
				  else{
					  commonTckBlack(data.errorMessage);
					  }
				  })
			},false)
    });	 
//计算价格   
    var totalWeight;var buyPrice;
    function totalPrice(){ 
		//价格变动，总价跳动动画开始
		 $(".allPriceLi").stop();
		 $(".allPriceLi #allPriceNum").stop();
		 $(".allPriceLi").animate({height:"0px",overflow:"hidden"},50);
		 $(".allPriceLi #allPriceNum").animate({marginTop:"-15px",opacity:"0"},50);
		 setTimeout(function(){
		 $(".allPriceLi").animate({height:"52px",overflow:"auto"});
		 $(".allPriceLi #allPriceNum").animate({marginTop:"0px",opacity:"1"});
		 },50); 
		//价格变动，总价跳动动画结束 
		 var buyPrice=0;  totalWeight=0; 	 	 
		 var buyLength=$(".buyNumber").length;
		 for(var i=0;i<buyLength;++i){
			 buyPrice=Number(buyPrice)+(Number($(".crowdPrice b").eq(i).html())*100*Number($(".buyNumber").eq(i).val())/100);
			 totalWeight=totalWeight+(Number(crowdGoods[i][7])*Number($(".buyNumber").eq(i).val()))
			 }
		//原始价格，不加优惠，不加抵扣，不加各种打折
	    var lastPrice=buyPrice;
		$("#allPriceNum b").html(lastPrice)//显示订单总价
		$(".lastPrice b").html(lastPrice)//显示实付款
	 };  
     totalPrice();

//验证电话号码方法
  function checkTel(callback){ 
	  var tel=$("#tel").val();	
        var partten = /^1[3,5,7,8]\d{9}$/;
          if(partten.test(tel))
          { }
		else
          {
     commonTckBlack("请填写正确的手机号码");
	   return;
          } 
	   callback(tel);
		  }
		  
//如果是在app打开
   if(wechat==false){
	   //初始化用户姓名电话地址
       setTimeout(function(){
		  bridgeApp('bridgeLogin',{}, function(response){
		    $("#name").val(response.userName);
			$("#tel").val(response.userTel);
			$("#contactName").val(response.userName);
			$("#contactTel").val(response.userTel);
		  
			   if(response.address.address==undefined){
				   $("#address").val(JSON.parse(response.address).address)
				   }
			   else{
				   $("#address").val(response.address.address)
				   }
	         }) ;
	      },500)  
	  //用户点击地址管理
    var addressSubmitData={};
    $("#addressButtonApp").click(function(e) {
         bridgeApp('userAddrSelect',{"selectedAddr":addressSubmitData},function(response){
			addressSubmitData=response.data;
			if(Number(response.success)==1){
		      $("#address").val(response.data.address+response.data.bldgNo);
			  $("#name").val(response.data.name);
			  $("#tel").val(response.data.phoneNo);
			 }
			})
       }); 
   }

//点击确认购买按钮
var stopBuy=false;var cityCode=0;
$("#submit").click(function(){
   switch (localStorage.cityCode.slice(0,4)){
	   case "0_0_":
	   cityCode="110000";
	   break;
	   case "0_1_":
	   cityCode="120000";
	   break;
	   case "0_2_":
	   cityCode="310000";
	   break;
	   case "0_3_":
	   cityCode="500000";
	   break;
	   case "0_4_":
	   cityCode="130000";
	   break;
	   case "0_5_":
	   cityCode="140000";
	   break;
	   case "0_6_":
	   cityCode="150000";
	   break;
	   case "0_7_":
	   cityCode="210000";
	   break;
	   case "0_8_":
	   cityCode="220000";
	   break;
	   case "0_9_":
	   cityCode="230000";
	   break;
	   case "0_10":
	   cityCode="320000";
	   break;
	   case "0_11":
	   cityCode="330000";
	   break;
	   case "0_12":
	   cityCode="340000";
	   break;
	   case "0_13":
	   cityCode="350000";
	   break;
	   case "0_14":
	   cityCode="360000";
	   break;
	   case "0_15":
	   cityCode="370000";
	   break;
	   case "0_16":
	   cityCode="410000";
	   break;
	   case "0_17":
	   cityCode="420000";
	   break;
	   case "0_18":
	   cityCode="430000";
	   break;
	   case "0_19":
	   cityCode="440000";
	   break;
	   case "0_20":
	   cityCode="450000";
	   break;
	   case "0_21":
	   cityCode="460000";
	   break;
	   case "0_22":
	   cityCode="510000";
	   break;
	   case "0_23":
	   cityCode="520000";
	   break;
	   case "0_24":
	   cityCode="530000";
	   break;
	   case "0_25":
	   cityCode="540000";
	   break;
	   case "0_26":
	   cityCode="610000";
	   break;
	   case "0_27":
	   cityCode="620000";
	   break;
	   case "0_28":
	   cityCode="630000";
	   break;
	   case "0_29":
	   cityCode="640000";
	   break;
	   case "0_30":
	   cityCode="650000";
	   break;
	   default:
	   cityCode="00";
	   break;
	   }
	  if(localStorage.cityCode=="0_11_0"){
		  cityCode="330100";
		  }
  //验证是否购买
var packingAmount;
      var extraAmount=initData.extraAmount;
	  if(extraAmount==""||extraAmount==null||extraAmount=="undefined"){
		  packingAmount=initData.packingAmount;
		  }
	  else{
		packingAmount=initData.packingAmount;
		for(var i in extraAmount){
			if(cityCode==extraAmount[i][0]){
				packingAmount=extraAmount[i][1]
				}
			}
		  }
  var freightData={
	     "extraAmount":packingAmount,
	     "configId":initData.configId,
		 "cityCode":cityCode,
		 "totalWeight":totalWeight,
		 "totalAmount":buyPrice
	   }
  $.ajax({
  type: 'POST',
  url: apiUrl+"/api/v2/express/calcFreight",
  data: freightData,
  success: function(data){
	     if(Number(data.success)==1){
			localStorage.freight=data.data.freightAmount;
			 }
		  else{
			   commonTckBlack(data.errorMessage);
			  }
	   },
  async:false
}); 
  
  var isBuy=false;var prodId=[];var prodNum=[];
  var buyNumLength=$(".buyNumber").length;
  for(var i=0;i<buyNumLength;++i){
	    prodId.push(crowdGoods[i][2]);
		prodNum.push($(".buyNumber").eq(i).val());
       if(Number($(".buyNumber").eq(i).val()>0)){
		   isBuy=true;
		   }	  
	  }
	  if(isBuy==false){
		  commonTckBlack("请选择至少一份商品购买");
		  return;
		  }
	if(stopBuy==true){
		return;
	}
  if(wechat==true){//如果是微信，获取姓名电话号码地址
   var tel1=$("#tel").val();
   var tel2=$("#applyTel").html();
   var name=$("#applyName").html();
   if(!tel1){tel1=tel2};
   var address=$("#applyAddress").html();
   var address2=$("#contactAddress").val();
   var code=$("#code").val();
   var partten = /^1[3,5,7,8]\d{9}$/;
   if(partten.test(tel1))
          { }
		else
          {
     commonTckBlack("请填写正确的手机号码");
	   return;
          }  
   if(code.length!=6||isNaN(code)==true){
	  commonTckBlack("请填写正确的验证码");
	   return;
	 }
  }else{//如果是APP，获取姓名电话号码地址
		var tel2=$("#tel").val();
        var name=$("#name").val();
		var address=$("#address").val();	
		if(crowdType=="ZC"||initData.crowdCode=="CW20160305"){
		 name=$("#applyName").html();
		 address=$("#applyAddress").html();
		  address2=$("#contactAddress").val();
		tel2=$("#applyTel").html();
			}
  }

	if($("#s_province option:selected").val()=="省份"||$("#s_city option:selected").val()=="地级市"||$("#s_county option:selected").val()=="市、县级市"){
		commonTckBlack("请将您地址的省市区填写完整");
	   return;
		}
	var time="";
	if(showTime==true){	
     time=$('#time option:selected').val();
    var clock=$('#clock option:selected').val();
	if(crowdCode!="ZC20160108"){
       if(time=="请选择收货日期"){
		commonTckBlack("请选择收货日期");
	   return;
	   } 
	   if($(".clockSpan").html()=="请选择收货时间"&&dateLimit==0){
		commonTckBlack("请选择收货时间");
	   return;
	   }
	 }
       time=time.slice(0,11);
       if(time=="今天"){
		   var CurrentMonth=String(current.getMonth()+1);
		   if(CurrentMonth.length==1){
			   CurrentMonth="0"+CurrentMonth;
			   }
			  var CurrentDate=String(current.getDate());
			   if(CurrentDate.length==1){
			   CurrentDate="0"+CurrentDate;
			   }
		   time=current.getFullYear()+"年"+CurrentMonth+"月"+CurrentDate+"日";
	     }
	   if($('.clockSpan').html()!="待定"){
		if(initData.crowdCode!="ZC20160119"){
			time=time+" "+$('.clockSpan').html();
			}
	   }
	}
   var personCount=$(".buyNumber").val();
   var allPrice=$("#allPriceNum b").html();
   var invoiceTitle=$("#applyInvoiceTitle").html();
   var invoice=$('#applyInvoice').html();
   var remark=$("#applyRemark").html();
   var inscription=$("#inscription input").val();
   if(invoiceTitle==null){
	   invoiceTitle="";
	   }
	    if(invoice==null){
	   invoice="";
	   } 
	   if(remark==null){
	   remark="";
	   }
   var partten = /^1[3,5,7,8]\d{9}$/;
	  if(isNull(name)){
	   commonTckBlack("请填写您的姓名");
	   return;
	    }
      if(partten.test(tel2))
          { }
		else
          {
      commonTckBlack("请填写正确的联系电话");
	   return;
          } 
	  if(isNull(address)){
	   commonTckBlack("请填写您的地址");
	   return;
	  }
	  if(isNull(address2)){
	   commonTckBlack("请填写您的详细地址");
	   return;
	  }  
	  if(wechat==false){//APP上存储订单数据
		  var applyData={
	        "userId":localStorage.userId,
			"crowdTitle":initData.crowdTitle,
			"address":address,
			"contactTel":tel2,
			"name":name,
			"time":time,
			"personCount":personCount,
			"totalAmount":allPrice,
			"crowdId":initData.crowdId,
			"inscription":inscription,
			"invoice":invoice,
			"invoiceTitle":invoiceTitle,
			"remark":remark,
			"prodId":prodId,
			"prodNum":prodNum,
			"cityCode":cityCode
			}
		localStorage.applyData=JSON.stringify(applyData);
		 bridgeApp('bridgePushVC',{'popNum':'0','vcType':'0','data':{"url":linkUrl+"content/crowd/toPay?crowdId="+initData.crowdId+"&userId="+localStorage.userId} /*★★★★★需修改url,跳转到填写订单页面*/}, function(response) {	
				      })
	  }else{//微信上存储订单数据
	$.post(initData.checkCodeApi,{"phoneNo":tel1,"checkCode":code,"deviceId":"w_"+initData.userOpenId},function(data){
	  if(Number(data.success==1)){
	   var applyData={
	        "userId":data.data.userId,
			"token":data.data.token,
			"refreshToken":data.data.refreshToken,
			"crowdTitle":initData.crowdTitle,
			"address":address,
			"tel":tel1,
			"contactTel":tel2,
			"name":name,
			"inscription":inscription,
			"personCount":personCount,
			"totalAmount":allPrice,
			"time":time,
			"crowdId":initData.crowdId,
			"invoiceTitle":invoiceTitle,
			"invoice":invoice,
			"remark":remark,
			"prodId":prodId,
			"prodNum":prodNum,
			"cityCode":cityCode
			}
		localStorage.applyData=JSON.stringify(applyData);
		window.location.href=initData.payUrl;}
		else{
		  commonTckBlack(data.errorMessage);
		}
	  })
	}
})

//弹出黑框提示，1.5秒后自动关闭
   function commonTckBlack(txt){
	var td='<div class="common_tck_black">';
	td=td+txt;
	td=td+'</div>';
    var node2=document.createElement("div");
        node2.setAttribute("id","common_tck");	 
		document.body.appendChild(node2); 
		document.getElementById("common_tck").innerHTML=td;	  
	    setTimeout(function(){document.body.removeChild(node2)},1500);
	}	
//判断是否空格
   function isNull( str ){
    if ( str == "" ) return true;
    var regu = "^[ ]+$";
    var re = new RegExp(regu);
    return re.test(str);
}
//输入框获取焦点自动弹出到可视区域（防止输入法框遮盖输入框）
$("input").focus(function(){
	var scollTop=$(this).offset().top;
	setTimeout(function(){window.scrollTo(0,scollTop-100);
	},200)
})
$("textarea").focus(function(){
	var scollTop=$(this).offset().top;
	setTimeout(function(){window.scrollTo(0,scollTop-100);
	},200)
})

//禁用换行
function checkEnter(e)
{
var et=e||window.event;
var keycode=et.charCode||et.keyCode;
if(keycode==13)
{
if(window.event)
window.event.returnValue = false;
else
e.preventDefault();//for firefox
}

}
